/* 
 * Copyright 2013 Sébastien Mouquet.
 * 
 * This file is part of ECovoiturage.
 * 
 * ECovoiturage is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ECovoiturage is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ECovoiturage. If not, see http://www.gnu.org/licenses/.
 */
package com.smouquet.ecovoiturage.ui.page;

import com.smouquet.ecovoiturage.ApplicationContext;
import com.smouquet.ecovoiturage.core.bean.Config;
import com.smouquet.ecovoiturage.core.exception.ConfigIOException;
import com.smouquet.ecovoiturage.core.exception.RunScriptException;
import com.smouquet.ecovoiturage.core.service.ConfigService;
import com.smouquet.ecovoiturage.core.service.DbMaintenanceService;
import com.smouquet.ecovoiturage.ui.NotificationUtil;
import com.smouquet.ecovoiturage.ui.Wizard;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Etape d'installation de l'application : création de la base de données.
 * 
 * @author sebastien.mouquet
 */
public class InstallWizardDatabaseStep extends HorizontalLayout implements Wizard.Step
{
    private Wizard wizard;
    private Config config;
    
    private Label message;
    
    
    public InstallWizardDatabaseStep()
    {
        layout();
    }
    
    
    private void layout()
    {
        message = new Label("");
        message.setSizeUndefined();
        
        addComponent(message);
        
        setSizeFull();
        setComponentAlignment(message, Alignment.MIDDLE_CENTER);
    }
    
    
    /**
     * Retourne la configuration saisie et enregistrée précédement.
     * 
     * @return La configuration
     */
    public Config getConfig() {
        return config;
    }
    
    
    @Override
    public void attachWizard(Wizard wizard)
    {
        this.wizard = wizard;
    }

    @Override
    public Component init()
    {
        wizard.setCaption("Installation - Installation de la base de données");
        wizard.setFinishEnabled(false);
        wizard.setCancelEnabled(false);
        
        Wizard.Step previousStep = wizard.getSteps().get(wizard.getCurrentStepIndex()-1);
        config = ((InstallWizardConfigStep)previousStep).getConfig();
        
        return this;
    }

    @Override
    public void run()
    {
        ConfigService configService = ApplicationContext.getInstance(ConfigService.class);
        DbMaintenanceService dbmaintenanceService = ApplicationContext.getInstance(DbMaintenanceService.class);
        
        try
        {
            message.setCaption("Test de connexion à la base de données...");
            
            Class.forName(config.getJdbcDriver());
            Connection cx = DriverManager.getConnection(config.getJdbcUrl(), config.getJdbcUser(), config.getJdbcPassword());
            
            if(cx != null)
            {   
                message.setCaption("Création de la base de donnée...");
                dbmaintenanceService.runAllScripts(cx, config);
                cx.close();

                message.setCaption("Enregistrement de la configuration...");
                configService.saveConfig(config);

                message.setCaption("Installation réussie !");
            }
            else
            {
                message.setCaption("Erreur de connexion à la base de données");
            }
            
        } catch(ClassNotFoundException ex) {
            message.setCaption("Erreur de connexion à la base de données");
            NotificationUtil.showExceptionNotification(ex);
        } catch(SQLException ex) {
            message.setCaption("Erreur de connexion à la base de données");
            NotificationUtil.showExceptionNotification(ex);
        } catch(RunScriptException ex) {
            message.setCaption("Erreur lors de la création la base de données");
            NotificationUtil.showExceptionNotification(ex);
        } catch(ConfigIOException ex) {
            message.setCaption("Erreur d'enregistrement de la configuration");
            NotificationUtil.showExceptionNotification(ex);
        } 
    }

    @Override
    public boolean onBeforePrevious() {
        return true;
    }

    @Override
    public void onAfterPrevious() {}

    @Override
    public boolean onBeforeNext() {
        return true;
    }

    @Override
    public void onAfterNext() {}

    @Override
    public boolean onBeforeFinish() {
        return true;
    }

    @Override
    public void onAfterFinish() {}

    @Override
    public boolean onBeforeCancel() {
        return true;
    }

    @Override
    public void onAfterCancel() {}
}
